package cn.gson.financial.kernel.service.impl;

import cn.gson.financial.kernel.constans.ComprehensiveParamesConstans;
import cn.gson.financial.kernel.dao.ComprehensiveParamsDao;
import cn.gson.financial.kernel.dao.ExportFileDao;
import cn.gson.financial.kernel.excelexport.*;
import cn.gson.financial.kernel.model.entity.*;
import cn.gson.financial.kernel.model.mapper.AccountSetsMapper;
import cn.gson.financial.kernel.model.mapper.ExportFileMapper;
import cn.gson.financial.kernel.model.vo.*;
import cn.gson.financial.kernel.service.*;
import cn.gson.financial.kernel.utils.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author：ywh
 * @Date：2023/4/17 11:13
 * @Description：
 */
@Service
public class ExportFileServiceImpl implements ExportFileService {

    @Autowired
    private VoucherService voucherService;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private ExportFileMapper exportFileMapper;
    @Autowired
    private VoucherDetailsService voucherDetailsService;
    @Autowired
    private AllSelectService allSelectService;
    @Autowired
    private ExportFileDao exportFileDao;
    @Autowired
    private ComprehensiveParamsDao comprehensiveParamsDao;
    @Autowired
    private AccountSetsMapper accountSetsMapper;


    @Override
    public String oldAccountImport(OldAccountImportBean oldAccountImportBean) {
        int i = exportFileMapper.oldAccountImport(oldAccountImportBean);
        //异步插入数据
//        exportFileDao.exportOldAccount(oldAccountImportBean.getId());
        if (i == 1) {
            return "添加成功！";
        }
        return "添加失败！";
    }

    @Override
    public Workbook allAccountExport(InputStream inputStream, int length,String companyName,String sheetName,String date) throws IOException {
        Workbook workbook = new XSSFWorkbook(inputStream);
        Sheet sheet = workbook.getSheet(sheetName);
        int lastRowNum = sheet.getLastRowNum();
        Row row = sheet.createRow(lastRowNum + 1);
        for (int j = 0; j < length; j++) {
            Cell cell = row.createCell(j);
            cell.setCellType(CellType.STRING);
            cell.setCellValue("");
        }
        row.getCell(0).setCellValue("编制单位：" + companyName);
        row.getCell(3).setCellValue(date);
        row.getCell(6).setCellValue("单位：元");

        //指定合并开始行、合并结束行 合并开始列、合并结束列
        CellRangeAddress rangeAddress = new CellRangeAddress(lastRowNum + 1, lastRowNum + 1, 0, 2);
        //添加要合并地址到表格
        sheet.addMergedRegion(rangeAddress);
        //指定合并开始行、合并结束行 合并开始列、合并结束列
        CellRangeAddress rangeAddress1 = new CellRangeAddress(lastRowNum + 1, lastRowNum + 1, 3, 5);
        //添加要合并地址到表格
        sheet.addMergedRegion(rangeAddress1);
        //指定合并开始行、合并结束行 合并开始列、合并结束列
        CellRangeAddress rangeAddress2 = new CellRangeAddress(lastRowNum + 1,lastRowNum + 1, 6,  7);
        //添加要合并地址到表格
        sheet.addMergedRegion(rangeAddress2);
        return workbook;
    }

    @Override
    public Workbook subLedgerExport(String subjectName,InputStream inputStream, int length, String companyName, String sheetName, String date) throws IOException {
        Workbook workbook = new XSSFWorkbook(inputStream);
        Sheet sheet = workbook.getSheet(sheetName);
        int lastRowNum = sheet.getLastRowNum();
        Row row = sheet.createRow(lastRowNum + 1);

        for (int j = 0; j < length; j++) {
            Cell cell = row.createCell(j);
            cell.setCellType(CellType.STRING);
            cell.setCellValue("");
        }
        row.getCell(0).setCellValue("编制单位：" + companyName);
        row.getCell(3).setCellValue("科目：" +  subjectName);
        row.getCell(6).setCellValue(date);
        row.getCell(8).setCellValue("单位：元");

        //指定合并开始行、合并结束行 合并开始列、合并结束列
        CellRangeAddress rangeAddress = new CellRangeAddress(lastRowNum + 1, lastRowNum + 1, 0, 2);
        //添加要合并地址到表格
        sheet.addMergedRegion(rangeAddress);
        //指定合并开始行、合并结束行 合并开始列、合并结束列
        CellRangeAddress rangeAddress1 = new CellRangeAddress(lastRowNum + 1, lastRowNum + 1, 3, 5);
        //添加要合并地址到表格
        sheet.addMergedRegion(rangeAddress1);
        //指定合并开始行、合并结束行 合并开始列、合并结束列
        CellRangeAddress rangeAddress2 = new CellRangeAddress(lastRowNum + 1,lastRowNum + 1, 6,  7);
        //添加要合并地址到表格
        sheet.addMergedRegion(rangeAddress2);
        return workbook;
    }


    // 总账 需要改
    @Override
    public List<AllAccountExport> downloadLedgerToExcel(Integer accSetsId,String startTime, String endTime ,String startSubject,String endSubject,Integer startLevel,Integer endLevel,boolean isOpen,boolean showNumPrice) throws ParseException {
        //当前查询账套
        AccountSets accountSets = accountSetsMapper.selectById(accSetsId);
        List<Subject> subjectList = subjectService.accountBookListByParam(startTime,endTime ,startSubject, endSubject, startLevel,endLevel,accSetsId,isOpen,showNumPrice,-2);

        List<Map<String, Object>> maps = voucherService.accountGeneralLedgerByParam(accountSets, startTime, endTime, startSubject, endSubject, startLevel, endLevel, isOpen, showNumPrice,-2,subjectList);
        for (Map<String, Object> map : maps) {
            subjectList.add((Subject) map.get("subject"));
        }
        List<AllAccountExport> list = new ArrayList<>();
        for (Subject subject : subjectList) {
            List<VoucherDetailVo> voucherDetailVoList = voucherService.summary1(accSetsId, subject.getId(), subject.getCode(), startTime,endTime, false);
            for (VoucherDetailVo voucherDetailVo : voucherDetailVoList) {
                AllAccountExport allAccountExport = new AllAccountExport();
                allAccountExport.setCode(subject.getCode());//科目编码
                allAccountExport.setName(subject.getName());//科目名称
                allAccountExport.setVoucherDate(new SimpleDateFormat("yyyy年第MM期").format(voucherDetailVo.getVoucherDate()));//期间
                allAccountExport.setSummary(voucherDetailVo.getSummary());//摘要
                allAccountExport.setDebitAmount(String.valueOf(voucherDetailVo.getDebitAmount()));//借方金额
                allAccountExport.setCreditAmount(String.valueOf(voucherDetailVo.getCreditAmount()));//贷方金额
                allAccountExport.setBalanceDirection(voucherDetailVo.getBalanceDirection());//方向
                allAccountExport.setBalance(String.valueOf(voucherDetailVo.getBalance()));//余额
                list.add(allAccountExport);
            }
        }
        return list;
    }

    @Override
    public List<SubLedger> downloadSubsidiaryToExcel(AccountBookVo vo) {
        List<VoucherDetailVo> list = new ArrayList<>();
        for (int i = 0; i <vo.getTimeList().size(); i++) {
            Date time = new Date();
            try {
                time = new SimpleDateFormat("yyyy-MM-dd").parse(vo.getTimeList().get(i));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            List<VoucherDetailVo> data1 = this.voucherService.accountBookDetails(vo.getAccountSetsId(),vo.getSubjectId(),time,vo.getSubjectCode(),true);
            for (int j = 0; j <data1.size() ; j++) {
                VoucherDetailVo vo1 = data1.get(i);
                list.add(vo1);
            }
        }

        List<SubLedger> subLedgerList = new ArrayList<>();
        for (VoucherDetailVo voucherDetailVo : list) {

            System.out.println(voucherDetailVo);
            SubLedger subLedger = new SubLedger();
            subLedger.setVoucherDate(new SimpleDateFormat("yyyy-MM-dd").format(voucherDetailVo.getVoucherDate()));
            subLedger.setWordCode(voucherDetailVo.getWord() + voucherDetailVo.getCode());
            if (voucherDetailVo.getSubjectName() != null && !voucherDetailVo.getSubjectName().equals("")){
                String[] split = voucherDetailVo.getSubjectName().split("-",2);
                subLedger.setSubjectCode(split[0]);
                subLedger.setSubjectName(split[1]);
            }else {
                subLedger.setSubjectCode("");
                subLedger.setSubjectName("");
            }
            subLedger.setSummary(voucherDetailVo.getSummary());
            subLedger.setDebitAmount(String.valueOf(voucherDetailVo.getDebitAmount()));
            subLedger.setCreditAmount(String.valueOf(voucherDetailVo.getCreditAmount()));
            subLedger.setBalanceDirection(voucherDetailVo.getBalanceDirection());
            subLedger.setBalance(String.valueOf(voucherDetailVo.getBalance()));
            subLedgerList.add(subLedger);
        }
        return subLedgerList;
    }

    @Override
    public List<AccountBalanceExport> downloadAccountBalanceToExcel(String companyName, String startTime, String endTime, String startSubject, String endSubject, int startLevel, int endLevel, int accountSetsId, Boolean showNumPrice, Boolean isOpen) {

        List<AccountBalanceExport> accountBalanceExportList = new ArrayList<>();
        List<BalanceVo> balanceVoList = subjectService.subjectBalanceByParam(startTime, endTime, startSubject, endSubject, startLevel, endLevel, accountSetsId, showNumPrice,isOpen,-1);
        for (BalanceVo balanceVo : balanceVoList) {
            AccountBalanceExport accountBalanceExport = new AccountBalanceExport();
            accountBalanceExport.setSubjectCode(balanceVo.getCode());
            accountBalanceExport.setSubjectName(balanceVo.getName());
            accountBalanceExport.setBeginningDebitBalance(String.valueOf(balanceVo.getBeginningDebitBalance()));
            accountBalanceExport.setBeginningCreditBalance(String.valueOf(balanceVo.getBeginningCreditBalance()));
            accountBalanceExport.setCurrentDebitAmount(String.valueOf(balanceVo.getCurrentDebitAmount()));
            accountBalanceExport.setCurrentDebitAmountNum(String.valueOf(balanceVo.getCurrentDebitAmountNum()));
            accountBalanceExport.setEndingDebitBalance(String.valueOf(balanceVo.getEndingDebitBalance()));
            accountBalanceExport.setEndingCreditBalance(String.valueOf(balanceVo.getEndingCreditBalance()));
            accountBalanceExportList.add(accountBalanceExport);
        }
        return  accountBalanceExportList;
    }

    @Override
    public Workbook accountBalanceExport(InputStream inputStream, int length, String companyName, String sheetName, String date,int writeTitleIndex) throws IOException {
        Workbook workbook = new XSSFWorkbook(inputStream);
        Sheet sheet = workbook.getSheet(sheetName);
        Row row = sheet.getRow(writeTitleIndex);
        row.getCell(0).setCellValue("编制单位：" + companyName);
        row.getCell(2).setCellValue(date);
        row.getCell(6).setCellValue("单位：元");
        return workbook;
    }

    // 序时账 需要改
    @Override
    public List<List<Object>> downloadChronologicalAccountToExcel(Integer accsetsId, String sTime, String eTime, String sWordCode, String eWordCode, String word, String summary, String sSubjectCode, String eSubjectCode, String sMoney, String eMoney, Integer sort,String columnIndex) {
        // 改
        List<ChronologicalAccountVo> chronologicalAccountVoList = voucherDetailsService.selectChronologicalAccountByParam(accsetsId, sTime, eTime, sWordCode, word, summary, sSubjectCode,sMoney,eMoney, eMoney,sort);
        List<Integer> voucherDetailsIdList = new ArrayList<>();
        for (ChronologicalAccountVo chronologicalAccountVo : chronologicalAccountVoList) {
            voucherDetailsIdList.add(chronologicalAccountVo.getVoucherDetailsId());
        }

        String[] titleHead = {"日期","凭证字号","摘要","科目名称","科目名称","借方数量","借方本币","贷方数量","贷方本币","制单人","审核人","附件数","备注"};
        HashMap<String, Object> hashMap = exportFileDao.getCategoryList(voucherDetailsIdList, titleHead, columnIndex);//设置表头
        List<List<Object>> objects = new ArrayList<>();
        List<Object> finTitleHeadList = (List<Object>) hashMap.get("finTitleHeadList");
        List<AuxiliaryVo> auxiliaryVoList = (List<AuxiliaryVo>) hashMap.get("auxiliaryVoList");
        List<String> filterTitle = (List<String>) hashMap.get("filterTitle");
        objects.add(finTitleHeadList);

        for (ChronologicalAccountVo chronologicalAccountVo : chronologicalAccountVoList) {
            List<Object> list = new ArrayList<>();
            list.add(chronologicalAccountVo.getVoucherData()+"");//日期
            list.add(chronologicalAccountVo.getVoucherWord()+chronologicalAccountVo.getVoucherWordNum()+"");//凭证字号
            list.add(chronologicalAccountVo.getSummary()+"");//摘要
            list.add(chronologicalAccountVo.getSubjectCode()+"");//科目编码
            list.add(chronologicalAccountVo.getSubjectName()+"");//科目名称
            list.add(chronologicalAccountVo.getCumulativeDebitNum()+"");//借方数量
            list.add(chronologicalAccountVo.getDebitAmount()+"");//借方本币
            list.add(chronologicalAccountVo.getCumulativeCreditNum()+"");//贷方数量
            list.add(chronologicalAccountVo.getCreditAmount()+"");//贷方本币
            //将辅助核算的值写入列表中，如果没有辅助核算，就写入空串
            list = exportFileDao.setAuxiliaryVo(list,auxiliaryVoList,filterTitle,chronologicalAccountVo.getVoucherDetailsId());
            list.add(BaseUtil.checkValueIsNull(chronologicalAccountVo.getCreateMember())) ;//制单人
            list.add(BaseUtil.checkValueIsNull(chronologicalAccountVo.getAuditMemberName())) ;//审核人
            list.add(BaseUtil.checkValueIsNull(String.valueOf(chronologicalAccountVo.getReceiptNum()))) ;//附件数
            list.add(BaseUtil.checkValueIsNull(chronologicalAccountVo.getRemark()) );//备注
            objects.add(list);

        }
        return objects;
    }

    @Override
    public List<List<Object>> voucherExport(VoucherSelectVo vo, String columnIndex ,Integer id) {
        List<Voucher> voucherListAll = allSelectService.voucherSelect(vo,id);
        List<Voucher> voucherList = new ArrayList<>();
        for (Voucher voucher : voucherListAll) {
            if (vo.getVoucherIdList().contains(String.valueOf(voucher.getId()))){
                voucherList.add(voucher);
            }
        }

        //获取明细id
        List<Integer> voucherDetailsIdList = new ArrayList<>();
        for (Voucher voucher : voucherList) {
            List<VoucherDetails> details = voucher.getDetails();
            for (VoucherDetails detail : details) {
                voucherDetailsIdList.add(detail.getId());
            }
        }
        String[] titleHead = {"日期","凭证号","行号","摘要","科目编码","科目名称","借方数量","借方单价","借方本币","贷方数量","贷方单价","贷方本币","制单人","审核人","附单据数","备注"};
        HashMap<String, Object> hashMap = exportFileDao.getCategoryList(voucherDetailsIdList, titleHead, columnIndex);//设置表头
        List<List<Object>> objects = new ArrayList<>();
        List<Object> finTitleHeadList = (List<Object>) hashMap.get("finTitleHeadList");
        List<AuxiliaryVo> auxiliaryVoList = (List<AuxiliaryVo>) hashMap.get("auxiliaryVoList");
        List<String> filterTitle = (List<String>) hashMap.get("filterTitle");
        objects.add(finTitleHeadList);

        for (Voucher voucher : voucherList) {
            List<VoucherDetails> details = voucher.getDetails();
            for (int i = 0; i <details.size(); i++) {
                List<Object> list = new ArrayList<>();
                list.add(new SimpleDateFormat("yyyy-MM-dd").format(voucher.getVoucherDate()));//日期
                list.add(voucher.getWord() + voucher.getCode());//凭证号word+code
                list.add(String.valueOf(i+1));//行号
                list.add(details.get(i).getSummary());//摘要
                list.add(details.get(i).getSubjectCode());//科目编码
                list.add(details.get(i).getSubjectName());//科目名称
                //借方本币!=null，说明方向是借方，否则为贷方
                if (details.get(i).getDebitAmount() != null){
                    list.add(String.valueOf(details.get(i).getNum()));//借方数量
                    list.add(String.valueOf(details.get(i).getPrice()));//借方单价
                    list.add(String.valueOf(details.get(i).getDebitAmount()));//借方本币
                    list.add("");//贷方数量
                    list.add("");//贷方单价
                    list.add("");//贷方本币
                }else {
                    list.add("");//借方数量
                    list.add("");//借方单价
                    list.add("");//借方本币
                    list.add(String.valueOf(details.get(i).getNum()));//贷方数量
                    list.add(String.valueOf(details.get(i).getPrice()));//贷方单价
                    list.add(String.valueOf(details.get(i).getCreditAmount()));//贷方本币
                }
                //将辅助核算的值写入列表中，如果没有辅助核算，就写入空串
                list = exportFileDao.setAuxiliaryVo(list,auxiliaryVoList,filterTitle,details.get(i).getId());
                list.add(String.valueOf(voucher.getCreateMemberReal()));//制单人
                list.add(voucher.getAuditMemberName());//审核人
                list.add(String.valueOf(voucher.getReceiptNum()));//附单据数
                list.add(voucher.getRemark());//备注
                objects.add(list);
            }
        }
        return objects;
    }

    @Override
    public List<User> findRealName(List<String> list) {
        return exportFileMapper.findRealName(list);
    }

    private VoucherExport setCategoryDetailsVo(List<CategoryDetailsVo> categoryDetailsVos, VoucherExport voucherExport) {
        if (categoryDetailsVos == null || categoryDetailsVos.size() != 0){
            for (CategoryDetailsVo categoryDetailsVo : categoryDetailsVos) {
                if (categoryDetailsVo.getAcName().equals("客户")){
                    voucherExport.setCustomerCode(categoryDetailsVo.getCode());//客户编号
                    voucherExport.setCustomerName(categoryDetailsVo.getName());//客户名称
                }else if(categoryDetailsVo.getAcName().equals("供应商")){
                    voucherExport.setSupplierCode(categoryDetailsVo.getCode());//供应商编码
                    voucherExport.setSupplierName(categoryDetailsVo.getName());//供应商名称
                }else if(categoryDetailsVo.getAcName().equals("职员")){
                    voucherExport.setEmployeeCode(categoryDetailsVo.getCode());//职员编码
                    voucherExport.setEmployeeName(categoryDetailsVo.getName());//职员名称
                }else if(categoryDetailsVo.getAcName().equals("部门")){
                    voucherExport.setDepartmentCode(categoryDetailsVo.getCode());//部门编码
                    voucherExport.setDepartmentName(categoryDetailsVo.getName());//部门名称
                }else if(categoryDetailsVo.getAcName().equals("项目")){
                    voucherExport.setProjectCode(categoryDetailsVo.getCode());//项目编码
                    voucherExport.setProjectName(categoryDetailsVo.getName());//项目名称
                }else if(categoryDetailsVo.getAcName().equals("现金流")){
                    voucherExport.setCashFlowCode(categoryDetailsVo.getCode());//现金流编码
                    voucherExport.setCashFlowName(categoryDetailsVo.getName());//现金流名称
                }
            }
        }
        //辅助核算为空 就不做任何处理
        return voucherExport;
    }

    @Override
    public Workbook cashFlowExport(InputStream inputStream, int length, String companyName, String sheetName, String date) throws IOException {
        Workbook workbook = new XSSFWorkbook(inputStream);
        Sheet sheet = workbook.getSheet(sheetName);
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <= 2; i++) {
            Row row = sheet.createRow(lastRowNum + i);
            for (int j = 0; j < length; j++) {
                Cell cell = row.createCell(j);
                cell.setCellType(CellType.STRING);
                cell.setCellValue("");
            }
            if (i == 1) {
                CellStyle cellStyle = workbook.createCellStyle(); //设置样式
                cellStyle.setAlignment(HorizontalAlignment.RIGHT); //设置水平方向的对其方式
                row.getCell(0).setCellStyle(cellStyle);
                row.getCell(0).setCellValue("小企业会计准则03表");
                //指定合并开始行、合并结束行 合并开始列、合并结束列
                CellRangeAddress rangeAddress = new CellRangeAddress(lastRowNum + i, lastRowNum + i, 0, 3);
                sheet.addMergedRegion(rangeAddress);
            } else if (i == 2) {
                row.getCell(0).setCellValue("编制单位：" + companyName);
                row.getCell(1).setCellValue(date);
                row.getCell(3).setCellValue("单位：元");

                //指定合并开始行、合并结束行 合并开始列、合并结束列
                CellRangeAddress rangeAddress = new CellRangeAddress(lastRowNum + i, lastRowNum + i, 1, 2);
                //添加要合并地址到表格
                sheet.addMergedRegion(rangeAddress);
            }
        }
        return workbook;
    }

    @Override
    public Workbook assetsLiabilitiesExporrt(InputStream inputStream, int length, String companyName, String sheetName, String date) throws IOException {
        Workbook workbook = new XSSFWorkbook(inputStream);
        Sheet sheet = workbook.getSheet(sheetName);
        CellStyle cellStyle = workbook.createCellStyle(); //设置样式
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <= 2; i++) {
            Row row = sheet.createRow(lastRowNum + i);
            for (int j = 0; j < length; j++) {
                Cell cell = row.createCell(j);
                cell.setCellType(CellType.STRING);
                cell.setCellValue("");
            }
            if (i == 1) {

                cellStyle.setAlignment(HorizontalAlignment.RIGHT); //设置水平方向的对其方式
                row.getCell(0).setCellStyle(cellStyle);
                row.getCell(0).setCellValue("小企业会计准则03表");
                //指定合并开始行、合并结束行 合并开始列、合并结束列
                CellRangeAddress rangeAddress = new CellRangeAddress(lastRowNum + i, lastRowNum + i, 0, 7);
                sheet.addMergedRegion(rangeAddress);
            } else if (i == 2) {
                row.getCell(0).setCellValue("编制单位：" + companyName);
                row.getCell(3).setCellValue(date);
                row.getCell(5).setCellValue("单位：元");
                row.getCell(5).setCellStyle(cellStyle);

                //指定合并开始行、合并结束行 合并开始列、合并结束列
                CellRangeAddress rangeAddress = new CellRangeAddress(lastRowNum + i, lastRowNum + i, 0, 2);
                //添加要合并地址到表格
                sheet.addMergedRegion(rangeAddress);
                //指定合并开始行、合并结束行 合并开始列、合并结束列
                CellRangeAddress rangeAddress1 = new CellRangeAddress(lastRowNum + i, lastRowNum + i, 3, 4);
                //添加要合并地址到表格
                sheet.addMergedRegion(rangeAddress1);
                //指定合并开始行、合并结束行 合并开始列、合并结束列
                CellRangeAddress rangeAddress2 = new CellRangeAddress(lastRowNum + i,lastRowNum + i, 5,  7);
                //添加要合并地址到表格
                sheet.addMergedRegion(rangeAddress2);
            }
        }
        return workbook;
    }

    @Override
    public List<ProfitExport> downloadProjectProfitToExcel(ReportTemplate allData,List<DepartmentOrProjectVO> views) {
        List<ProfitExport> list = new ArrayList<>();
        List<ReportTemplateItems> items = allData.getItems();
        for (ReportTemplateItems item : items) {
            Integer itemId = item.getId();
            String title = item.getTitle();
            Integer lineNum = item.getLineNum();
            for (DepartmentOrProjectVO view : views) {
                if (view.getDepartentProjectName().equals("合计")){
                    ReportDataVo reportDataVo = view.getMap().get(itemId);
                    if (reportDataVo != null ){
                        ProfitExport profitExport = new ProfitExport();
                        profitExport.setProject(title);
                        profitExport.setLineNo(String.valueOf(lineNum));
                        profitExport.setCurrentAmount(String.valueOf(reportDataVo.getCurrentPeriodAmount()));
                        profitExport.setAccumulatedAmountThisYear(String.valueOf(reportDataVo.getCurrentYearAmount()));
                        list.add(profitExport);
                    }
                }
            }
        }
        return list;
    }

    @Override
    public List<ProfitExport> downloadProfitToExcel(ReportTemplate allData,Map<Integer, ReportDataVo> integerReportDataVoMap) {
        List<ProfitExport> list = new ArrayList<>();
        List<ReportTemplateItems> items = allData.getItems();
        for (ReportTemplateItems item : items) {
            System.out.println("item===" + item);
            ProfitExport profitExport = new ProfitExport();
            Integer itemId = item.getId();
            String title = item.getTitle();
            Integer lineNum = item.getLineNum();
            Integer level = item.getLevel();
            String empty = "";
            for (Integer i = 1; i <= level; i++) {
                if ( i != 1){
                    empty += "  ";
                }
            }

            profitExport.setProject(empty+title);
            profitExport.setLineNo(String.valueOf(lineNum));
            ReportDataVo reportDataVo = integerReportDataVoMap.get(itemId);
            System.out.println("reportDataVo===" + reportDataVo);
            if (reportDataVo != null) {
                profitExport.setCurrentAmount(String.valueOf(reportDataVo.getCurrentPeriodAmount()).equals("0.0")?"":String.valueOf(reportDataVo.getCurrentPeriodAmount()));
                profitExport.setAccumulatedAmountThisYear(String.valueOf(reportDataVo.getCurrentYearAmount()).equals("0.0")?"":String.valueOf(reportDataVo.getCurrentYearAmount()));
            }else {
                profitExport.setCurrentAmount("");
                profitExport.setAccumulatedAmountThisYear("");
            }
            list.add(profitExport);
        }
        return list;
    }

    @Override
    public int findMaxOldAccountTaskId(int accountSetsId) {
        return exportFileDao.findMaxOldAccountTaskId(accountSetsId);
    }

    @Override
    public Object findState(String mobile) {
        return exportFileDao.findState(mobile);
    }

    @Override
    public List<CashFlowExport> downloadCashFlowToExcel(ReportTemplate allData,Map<String, BottomTableVo> bottomTableVoMap) {
        List<CashFlowExport> list = new ArrayList<>();
        List<ReportTemplateItems> items = allData.getItems();
        for (ReportTemplateItems item : items) {
            System.out.println("item===" + item);
            CashFlowExport cashFlowExport = new CashFlowExport();
            Integer itemId = item.getId();
            String title = item.getTitle();
            Integer lineNum = item.getLineNum();
            Integer level = item.getLevel();
            String empty = "";
            for (Integer i = 1; i <= level; i++) {
                if ( i != 1){
                    empty += "  ";
                }
            }
            cashFlowExport.setProject(empty+title);
            cashFlowExport.setLineNo(String.valueOf(lineNum));
            BottomTableVo bottomTableVo = bottomTableVoMap.get(String.valueOf(itemId));
            System.out.println("bottomTableVo===" + bottomTableVo);
            if (bottomTableVo != null) {
                cashFlowExport.setCurrentAmount(bottomTableVo.getAmountMonth() == null || bottomTableVo.getAmountMonth().equals("0.0")?"":bottomTableVo.getAmountMonth());
                cashFlowExport.setAccumulatedAmountThisYear(bottomTableVo.getAmountYear() == null || bottomTableVo.getAmountYear().equals("0.0")?"":bottomTableVo.getAmountYear());
            }else {
                cashFlowExport.setCurrentAmount("");
                cashFlowExport.setAccumulatedAmountThisYear("");
            }

            if (item.getFormulas() != null && item.getFormulas().size() > 0){
                Double monthAmount = 0.0;
                Double yearAmount = 0.0;
                for (ReportTemplateItemsFormula f : item.getFormulas()) {
                    Object calculation = f.getCalculation();//获取是+还是-
                    String fromTag = f.getFromTag();

                    if (calculation.equals("+")){
                        monthAmount +=  bottomTableVoMap.get(fromTag).getAmountMonth() == null?0.0: Double.parseDouble(bottomTableVoMap.get(fromTag).getAmountMonth());
                        yearAmount += bottomTableVoMap.get(fromTag).getAmountYear() == null?0.0:Double.parseDouble(bottomTableVoMap.get(fromTag).getAmountYear());
                    }
                    if (calculation.equals("-")){
                        monthAmount -=  bottomTableVoMap.get(fromTag).getAmountMonth() == null?0.0: Double.parseDouble(bottomTableVoMap.get(fromTag).getAmountMonth());
                        yearAmount -= bottomTableVoMap.get(fromTag).getAmountYear() == null?0.0:Double.parseDouble(bottomTableVoMap.get(fromTag).getAmountYear());
                    }
                }
                cashFlowExport.setCurrentAmount(String.valueOf(monthAmount).equals("0.0")?"":String.valueOf(monthAmount));
                cashFlowExport.setAccumulatedAmountThisYear(String.valueOf(yearAmount).equals("0.0")?"":String.valueOf(yearAmount));
            }
            list.add(cashFlowExport);
        }
        return list;
    }

    @Override
    public List<AssetsLiabilitiesExport> downloadAssetsLiabilitiesToExcel(ReportTemplate allData,Map<Integer, ReportDataVo> integerReportDataVoMap) {
        List<AssetsLiabilitiesExport> list = new ArrayList<>();
        List<ReportTemplateItems> items = allData.getItems();
        List<ReportTemplateItems> itemsType0 =  new ArrayList<>();
        List<ReportTemplateItems> itemsType1 =  new ArrayList<>();
        System.out.println("===========");
        for (ReportTemplateItems item : items) {
            System.out.println(item);
            if (item.getType().equals("0") || item.getType() == 0){
                itemsType0.add(item);
            }else {
                itemsType1.add(item);
            }
        }

        if (itemsType0.size()>itemsType1.size()){
            for (int i = 0; i < itemsType0.size(); i++) {
                AssetsLiabilitiesExport assetsLiabilitiesExport = new AssetsLiabilitiesExport();
                Integer itemId0 = itemsType0.get(i).getId();
                String title0 = itemsType0.get(i).getTitle();
                Integer lineNum0 = itemsType0.get(i).getLineNum();
                Integer level0 = itemsType0.get(i).getLevel();
                assetsLiabilitiesExport.setAsset(writeLevel(level0,title0));
                assetsLiabilitiesExport.setALineNo(String.valueOf(lineNum0));
                ReportDataVo reportDataVo0 = integerReportDataVoMap.get(itemId0);
                if (reportDataVo0 != null){
                    assetsLiabilitiesExport.setAEndingBalance(String.valueOf(reportDataVo0.getCurrentPeriodAmount()).equals("0.0")?"":String.valueOf(reportDataVo0.getCurrentPeriodAmount()));
                    assetsLiabilitiesExport.setABeginningBalance(String.valueOf(reportDataVo0.getCurrentYearAmount()).equals("0.0")?"":String.valueOf(reportDataVo0.getCurrentYearAmount()));
                }else {
                    assetsLiabilitiesExport.setAEndingBalance("");
                    assetsLiabilitiesExport.setABeginningBalance("");
                }
                //防止空指针异常
                if (itemsType1.size() > i){
                    Integer itemId1 = itemsType1.get(i).getId();
                    String title1 = itemsType1.get(i).getTitle();
                    Integer lineNum1 = itemsType1.get(i).getLineNum();
                    Integer level1 = itemsType1.get(i).getLevel();
                    assetsLiabilitiesExport.setLiabilitiesEquity(writeLevel(level1,title1));
                    assetsLiabilitiesExport.setLLineNo(String.valueOf(lineNum1));
                    ReportDataVo reportDataVo1 = integerReportDataVoMap.get(itemId1);
                    if (reportDataVo1 != null){
                        assetsLiabilitiesExport.setLEndingBalance(String.valueOf(reportDataVo1.getCurrentPeriodAmount()).equals("0.0")?"":String.valueOf(reportDataVo1.getCurrentPeriodAmount()));
                        assetsLiabilitiesExport.setLBeginningBalance(String.valueOf(reportDataVo1.getCurrentYearAmount()).equals("0.0")?"":String.valueOf(reportDataVo1.getCurrentYearAmount()));
                    }else {
                        assetsLiabilitiesExport.setLEndingBalance("");
                        assetsLiabilitiesExport.setLBeginningBalance("");
                    }

                }else {
                    assetsLiabilitiesExport.setLiabilitiesEquity("");
                    assetsLiabilitiesExport.setLLineNo("");
                    assetsLiabilitiesExport.setLEndingBalance("");
                    assetsLiabilitiesExport.setLBeginningBalance("");
                }
                list.add(assetsLiabilitiesExport);
            }
        }else {
            for (int i = 0; i < itemsType1.size(); i++) {
                AssetsLiabilitiesExport assetsLiabilitiesExport = new AssetsLiabilitiesExport();
                Integer itemId1 = itemsType1.get(i).getId();
                String title1 = itemsType1.get(i).getTitle();
                Integer lineNum1 = itemsType1.get(i).getLineNum();
                Integer level1 = itemsType1.get(i).getLevel();
                assetsLiabilitiesExport.setLiabilitiesEquity(writeLevel(level1,title1));
                assetsLiabilitiesExport.setLLineNo(String.valueOf(lineNum1));

                ReportDataVo reportDataVo1 = integerReportDataVoMap.get(itemId1);
                if (reportDataVo1 != null){
                    assetsLiabilitiesExport.setLEndingBalance(String.valueOf(reportDataVo1.getCurrentPeriodAmount()).equals("0.0")?"":String.valueOf(reportDataVo1.getCurrentPeriodAmount()));
                    assetsLiabilitiesExport.setLBeginningBalance(String.valueOf(reportDataVo1.getCurrentYearAmount()).equals("0.0")?"":String.valueOf(reportDataVo1.getCurrentYearAmount()));
                }else {
                    assetsLiabilitiesExport.setLEndingBalance("");
                    assetsLiabilitiesExport.setLBeginningBalance("");
                }
                //防止空指针异常
                if (itemsType0.size() > i){
                    Integer itemId0 = itemsType0.get(i).getId();
                    String title0 = itemsType0.get(i).getTitle();
                    Integer lineNum0 = itemsType0.get(i).getLineNum();
                    Integer level0 = itemsType0.get(i).getLevel();
                    assetsLiabilitiesExport.setAsset(writeLevel(level0,title0));
                    assetsLiabilitiesExport.setALineNo(String.valueOf(lineNum0));
                    ReportDataVo reportDataVo0 = integerReportDataVoMap.get(itemId0);
                    if (reportDataVo0 != null){
                        assetsLiabilitiesExport.setAEndingBalance(String.valueOf(reportDataVo0.getCurrentPeriodAmount()).equals("0.0")?"":String.valueOf(reportDataVo0.getCurrentPeriodAmount()));
                        assetsLiabilitiesExport.setABeginningBalance(String.valueOf(reportDataVo0.getCurrentYearAmount()).equals("0.0")?"":String.valueOf(reportDataVo0.getCurrentYearAmount()));
                    }else {
                        assetsLiabilitiesExport.setAEndingBalance("");
                        assetsLiabilitiesExport.setABeginningBalance("");
                    }
                }else {
                    assetsLiabilitiesExport.setAsset("");
                    assetsLiabilitiesExport.setALineNo("");
                    assetsLiabilitiesExport.setAEndingBalance("");
                    assetsLiabilitiesExport.setABeginningBalance("");
                }
                list.add(assetsLiabilitiesExport);
            }
        }
        return list;
    }

    private String writeLevel(Integer level,String title){
        String empty = "";
        for (Integer j = 1; j <= level; j++) {
            if ( j != 1){
                empty += "  ";
            }
        }
        return empty + title;
    }
}
